<template>
  <van-nav-bar left-arrow left-text="返回" title="请新增收货地址"></van-nav-bar>
  <van-form @submit="onSubmit" class="addAddress">
    <van-cell-group inset>
      <!-- 姓名 -->
      <van-field
      v-model="real_name"
      name="姓名"
      label="姓名"
      placeholder="收货人姓名"
      :rules="[{ required: true, message: '请填写收货人姓名' }]"
      />
      <!-- 电话 -->
      <van-field
      v-model="phone"
      name="电话"
      label="电话"
      placeholder="收货人电话号码"
      :rules="[{ required: true, message: '请填写电话号码' }]"
      />
      <!-- 地区 -->
      <van-field
      v-model="fieldValue"
      is-link
      readonly
      label="地区"
      placeholder="请选择所在地区"
      @click="show = true"
      />
      <!-- 地址弹框 -->
      <van-popup v-model:show="show" round position="bottom">
        <van-cascader
          v-model="area"
          title="请选择所在地区"
          :field-names="fieldNames"
          :options="options"
          @close="show = false"
          @finish="onFinish"
        />
      </van-popup>
      <!-- 详细地址 -->
      <van-field
        v-model="detail"
        name="详细地址"
        label="详细地址"
        placeholder="详细地址信息"
        :rules="[{ required: true, message: '请填写电话号码' }]"
      />
    </van-cell-group>
    <!-- 开关选择默认地址 -->
    <van-cell-group inset>
      <van-field name="switch" label="设为默认地址" input-align="right">
        <template #input>
          <van-switch v-model="is_default" size="20" />
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit"
      @click="handleAdd">提交
      </van-button>
    </div>
  </van-form>
</template>
<script setup>
import { NavBar as VanNavBar, Button as VanButton, Form as VanForm, 
  CellGroup as VanCellGroup, Field as VanField, Popup as VanPopup,
  Cascader as VanCascader, Switch as VanSwitch } from 'vant'
import { getCityList, addAddress } from '@/api/address'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
// 姓名
const real_name = ref('')
// 电话
const phone = ref('')
// 地区
const area = ref('')
// 详细地址
const detail = ref('')
// 地址弹框是否显示
const show = ref(false)
// 选择默认的开关
const is_default = ref(false)
// 选择地区后输入框显示的内容
const fieldValue = ref('')

// 通过 field-names 属性可以自定义 options 里的字段名称。
const fieldNames = {
  text: 'n',
  value: 'v',
  children: 'c',
}

// 选项列表，children 代表子选项，支持多级嵌套
const options = ref([])

// 得到的数据还有更深的层，所有需要处理数据
const processData = data => {
  data.forEach(item => {
    // 得到的数据 如果 C 属性的 为空 那么就删除c属性
    if (item.c.length === 0){
      delete item.c
    } else {
      // 有c 说明是省或市 如果再有空的c 就进行递归处理
      processData(item.c)
    }
  })
  return data
}
// 全部选项选择完毕后，会触发 finish 事件
const onFinish = ({ selectedOptions }) => {
  show.value = false
  // console.log(selectedOptions)
  fieldValue.value = selectedOptions.map((option) => option.n).join('/')
  // 为提交新增地址的请求做参数存储
  address = {
    province: selectedOptions[0].n,
    city: selectedOptions[1].n,
    city_id: selectedOptions[1].v,
    district: selectedOptions[2].n,
  }
}


// ------  获取省市区列表   ------- 
const initCityList = async () => {
  const { data } = await getCityList()
  console.log(data)
  if (data.status !== 200) { return }
  options.value = processData(data.data)
}
initCityList()



// ------ 提交数据   -----
// 存储添加地址后的表单数据  
let address = {}
// 接受传值
// const { carId } = defineProps({
//   carId: String  // 别的地方也可以有新增地址的跳转 所以不需要required
// })
const route = useRoute()
const carId = route.query.carId
const handleAdd = async () => {
  const { data } = await addAddress({
    address,
    // 新增地址时id为0 id为其他数据时此时的状态为编辑状态
    id: 0,
    phone: phone.value,
    real_name: real_name.value,
    detail: detail.value,
    is_default: is_default.value
  })
  // console.log(data)
  if (data.status !== 200){ return }
  if(carId){router.push({
    name: 'order-confirm',
    query: {
      carId
    }
  })
  } else {
    router.push('/user')
  }
}

</script>
<style lang='scss' scoped>
.addAddress{
  background-color: #f7f7f7;
  padding: 0;
}
.van-cell-group{
  margin-bottom: 10px;
}
</style> 